package com.hp.tiger.chapter10;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author XavierDong
 **/
public class ThreadLocalSimulatorTest {

    private static final ThreadLocalSimulator<String> threadLocal = new ThreadLocalSimulator<String>() {
        public String initiaValue() {
            return "No value!";
        }
    };

    //    seed
    private static final Random RANDOM = new Random(System.currentTimeMillis());

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(() -> {
            threadLocal.set("Thread-T1");
            try {
                TimeUnit.MILLISECONDS.sleep(RANDOM.nextInt(1000));
                System.out.println(Thread.currentThread().getName() + " " + threadLocal.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.start();

        Thread t2 = new Thread(() -> {
            threadLocal.set("Thread-T2");
            try {
                TimeUnit.MILLISECONDS.sleep(RANDOM.nextInt(1000));
                System.out.println(Thread.currentThread().getName() + " " + threadLocal.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t2.start();
        t1.join();
        t2.join();
        System.out.println("==================");
        System.out.println(Thread.currentThread().getName() + " " + threadLocal.get());

    }
}
